package com.it.sun.yuebike.framework.mybatis;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.it.sun.yuebike.framework.model.vo.AttachmentVO;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName com.it.sun.yuebike.framework.mybatis.AttachmentsTypeHandler
 * @Author sunmannian
 * @Date 2021/6/6 18:48
 * @Version V1.0
 * Description  <附件ORM处理器>
 * Copyright (C) 北京中电兴发科技有限公司  since 2021/6/6
 */
public class AttachmentsTypeHandler extends BaseTypeHandler<List<AttachmentVO>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<AttachmentVO> parameter, JdbcType jdbcType) throws SQLException {
        String value = JSONUtil.toJsonStr(parameter);
        ps.setString(i, value);
    }

    @Override
    public List<AttachmentVO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return parseStr2Attachments(value);
    }

    @Override
    public List<AttachmentVO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return parseStr2Attachments(value);
    }

    @Override
    public List<AttachmentVO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return parseStr2Attachments(value);
    }

    private List<AttachmentVO> parseStr2Attachments(String value) {
        return StrUtil.isBlank(value) ? CollectionUtil.newArrayList() : JSONUtil.toList(value, AttachmentVO.class);
    }
}



